﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace VitCode.ObjectResolutionHelper
{
    public class ExcelOperateHelper
    {
        public static string GetEndCellName(string startCellName, int rowAddNum, int columnAddNum)
        {
            int[] startCellCoordinate = GetCoordinate(startCellName);
            int endCellRowNum = startCellCoordinate[0] + rowAddNum;
            int endCellColumnNum = startCellCoordinate[1] + columnAddNum;
            string cellColumnName = "";
            for (int i = 0; i < endCellColumnNum.ToString().Length; i++)
                cellColumnName = GetColumnCharString(endCellColumnNum, i + 1) + cellColumnName;
            return cellColumnName + endCellRowNum.ToString();
        }

        public static int[] GetCoordinate(string cellName)
        {
            int columnIndex = 0;
            int rowIndex = 0;
            char[] chars = cellName.ToCharArray();
            int charCount = 0, numCount = 0;
            for (int i = chars.Length - 1; i >= 0; i--)
            {
                if (chars[i] >= '0' && chars[i] <= '9')
                {
                    rowIndex += Convert.ToInt32(Math.Pow(10, numCount)) * (Convert.ToInt32(chars[i]) - 48);
                    numCount++;
                }
                else if (chars[i] >= 'A' && chars[i] <= 'Z')
                {
                    columnIndex += Convert.ToInt32(Math.Pow(26, charCount)) * (Convert.ToInt32(chars[i]) - 64);
                    charCount++;
                }
                else
                    throw new ArgumentOutOfRangeException("单元格名称不符合规格");
            }
            int[] returnValue = new int[] { rowIndex, columnIndex };
            return returnValue;
        }

        public static string GetColumnCharString(int endCellColumnNum, int weiShu)
        {
            if (endCellColumnNum == 1 || endCellColumnNum > Math.Pow(26, weiShu - 1))
                return
                    Convert.ToChar(Convert.ToInt32(Math.Floor(Convert.ToDouble(endCellColumnNum) / Math.Pow(26, weiShu - 1))) % 26 + 64).
                        ToString();
            else
                return "";
        }

        
    }
}
